<!--  -->
<template>
  <div class="channel-edit">
    <!-- 我的频道 -->
    <van-cell :border="false">
      <div
        slot="title"
        class="title-text"
      >我的频道</div>
      <van-button
        class="edit-btn"
        type="danger"
        plain
        round
        size="mini"
        @click="isEdit = !isEdit"
      >{{ isEdit ? '完成': '编辑'}}</van-button>
    </van-cell>
    <van-grid
      :gutter="10"
      class="my-grid"
    >
      <van-grid-item
        class="grid-item"
        v-for="(channel,index) in myChannels"
        :key="index"
        @click="onMyChannelClick(channel,index)"
      >
        <van-icon
          v-show="isEdit && !fixedChannels.includes(channel.id)"
          slot="icon"
          name="clear"
        ></van-icon>
        <span
          slot="text"
          class="text"
          :class="{ active: index === active }"
        >{{channel.name}}</span>
      </van-grid-item>
    </van-grid>

    <!-- 频道推荐 -->
    <van-cell :border="false">
      <div
        slot="title"
        class="title-text"
      >频道推荐</div>
    </van-cell>
    <van-grid
      :gutter="10"
      class="recommed-grid"
    >
      <van-grid-item
        class="grid-item"
        icon="plus"
        v-for="(channel,index) in recommendChannels"
        :key="index"
        :text="channel.name"
        @click="onAddChannel(channel)"
      />
    </van-grid>
  </div>
</template>

<script>
import { getAllChannels, addUserChannel, deleteChannel } from '@/api/channel'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'ChannelEdit',
  components: {},
  props: {
    myChannels: {
      type: Array,
      required: true
    },
    active: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      allChannels: [], // 所有频道
      isEdit: false, // 判断是编辑状态 还是非编辑状态
      fixedChannels: [0] // 固定频道， 不允许删除
    }
  },
  computed: {
    ...mapState(['user']),
    // 计算属性会观测内部依赖数据的变化
    // 如果依赖的数据发生变化 则计算属性会重新执行
    recommendChannels () {
      // 数组的 filter 方法 遍历数组 把符合条件的的元素存储到新数组中并返回
      return this.allChannels.filter((channel) => {
        return !this.myChannels.find((myChannel) => {
          return myChannel.id === channel.id
        })
      })
    }
    // const channels = []
    // this.allChannels.forEach(channel => {
    //   const ret = this.myChannels.find(myChannel => {
    //     return myChannel.id === channel.id
    //   })
    //   // 如果我的频道中不包括该频道项，则收集到推荐频道中
    //   if (!ret) {
    //     channels.push(channel)
    //   }
    // })
    // // 把计算结果放回
    // return channels
  },
  watch: {},
  created () {
    this.loadAllChannels()
  },
  mounted () {},
  methods: {
    async loadAllChannels () {
      try {
        const { data } = await getAllChannels()
        this.allChannels = data.data.channels
        console.log(data)
      } catch (error) {
        console.log('数据获取失败', error)
      }
    },
    async onAddChannel (channel) {
      this.myChannels.push(channel)
      try {
      // 数据持久化处理
        if (this.user) {
        // 已登录，吧数据请求接口放到线上
          await addUserChannel({
            id: channel.id, // 频道ID
            seq: this.myChannels.length // 序号
          })
          console.log('执行到这里了')
        } else {
        // 未登录，把数据放到本地
          setItem('TOUTIAO_CHANNELS', this.myChannels)
        }
      } catch (error) {
        console.log(error)
        this.$toast('保存失败，请稍后重试', error)
      }
      // 未登录， 把数据存储到本地
      // 已登录， 把数据请求接口放到线上
    },
    onMyChannelClick (channel, index) {
      if (this.isEdit) {
        // 如果是规定频道，则不能删除
        if (this.fixedChannels.includes(channel.id)) {
          return
        }
        // 如果是编辑状态 执行删除频道
        // 参数1：要删除的元素的索引
        // 参数2： 要删除的个数，如果不写，则从参数1开始一直删除到最后
        // 删除频道项
        this.myChannels.splice(index, 1)
        if (index <= this.active) {
          // 让激活频道的索引 -1
          this.$emit('update-active', this.active - 1, true)
        }

        // 持久化处理
        this.deleteChannel(channel)
      } else {
        // 非编辑状态 则执行切换频道
        this.$emit('update-active', index, false)
      }
    },

    async deleteChannel (channel) {
      try {
        if (this.user) {
        // 已登录, 则将数据更新到线上
          await deleteChannel(channel)
        } else {
        // 未登录，将数据更新到本地
          setItem('TOUTIAO_CHANNELS', this.myChannels)
        }
      } catch (error) {
        this.$toast('删除失败，请稍后重试')
      }
    }
  }
}
</script>
<style lang='less' scoped>
.channel-edit {
  padding: 85px 0;

  .title-text {
    font-size: 32px;
    color: #333;
  }

  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }

  .grid-item {
    width: 160px;
    height: 86px;
    /deep/ .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }

  /deep/ .recommed-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
      }
    }
  }

  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        top: -10px;
        right: -10px;
        font-size: 30px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }
}
</style>
